import os
import subprocess
import json

NORMALIZED_FILES_LOG = "normalized_files.json"

def load_normalized_files():
    if os.path.exists(NORMALIZED_FILES_LOG):
        with open(NORMALIZED_FILES_LOG, "r") as f:
            return json.load(f)
    return []

def save_normalized_files(normalized_files):
    with open(NORMALIZED_FILES_LOG, "w") as f:
        json.dump(normalized_files, f, indent=4)

def normalize_audio(input_path):
    normalized_files = load_normalized_files()

    if os.path.isdir(input_path):
        # 遍历目录处理所有音频文件
        for root, dirs, files in os.walk(input_path):
            for file in files:
                if file.endswith(('.mp3')):
                    file_path = os.path.join(root, file)
                    if file_path in normalized_files:
                        print(f"Skipping already normalized file: {file_path}")
                        continue
                    normalize_file(file_path, normalized_files)
    elif os.path.isfile(input_path) and input_path.endswith(('.mp3')):
        if input_path in normalized_files:
            print(f"Skipping already normalized file: {input_path}")
        else:
            normalize_file(input_path, normalized_files)
    else:
        print(f'{input_path} is not a valid audio file or directory.')

    save_normalized_files(normalized_files)

def normalize_file(file_path, normalized_files):
    try:
        # 临时文件路径，确保扩展名为 .mp3
        temp_file = f"{file_path}.normalized.mp3"
        # 使用 ffmpeg-normalize 处理音频
        command = [
            'ffmpeg-normalize',
            file_path,
            '--output', temp_file,  # 将输出写入临时文件

            # 都使用默认值
            # '--target-level', '-23',  # 设置目标响度
            # '--loudness-range-target', '7',  # 限制动态范围
            # '--true-peak', '-1',  # 设置真实峰值
            '--force',  # 强制覆盖输出文件
            '--audio-codec', 'libmp3lame',  # 明确指定编码器（适用于 MP3 文件）
            '-b:a', '128k',  # 设置比特率为 128 kbps
        ]
        subprocess.run(command, check=True)
        os.replace(temp_file, file_path)  # 替换原文件

        # 将文件路径记录到日志
        normalized_files.append(file_path)
        print(f"Successfully normalized {file_path}")
    except subprocess.CalledProcessError as e:
        print(f"Error processing {file_path}: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")

if __name__ == "__main__":
    input_directory = '../RollGame/assets'  # 替换为你的音频文件目录
    normalize_audio(input_directory)
